package cn.yunyichina.utils.commons;

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XmlUtils {

    /**
     * 解析入参实体参数
     */
    private static final String XML_ENTITY = "entity";


    /**
     * 解析入参实体开头
     */
    private static final String XML_HEAD = "<" + XML_ENTITY + ">";

    /**
     * 解析入参实体结尾
     */
    private static final String XML_FOOT = "</" + XML_ENTITY + ">";

    public static <T> T xmlToObject(String xml, Class<T> clazz) {
        XStream stream = new XStream();
        stream.ignoreUnknownElements();
        StringBuffer sb = new StringBuffer();
        sb.append(XML_HEAD);
        sb.append(xml);
        sb.append(XML_FOOT);
        stream.alias(XML_ENTITY, clazz);
        stream.registerConverter(new IntegerConverter());
        return (T) stream.fromXML(sb.toString());
    }

    public static String buildMapXML(Map<String, String> params) {
        Element xml = DocumentHelper.createElement("xml");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            xml.addElement(entry.getKey()).addCDATA(entry.getValue());
        }
        return xml.asXML();
    }

    public static String buildMapXML(Map<?, ?> params, String root) {
        Element xml = DocumentHelper.createElement(root);

        for (Map.Entry<?, ?> entry : params.entrySet()) {
            xml.addElement((String) entry.getKey()).addCDATA((String) entry.getValue());
        }

        return xml.asXML();
    }

    public static String buildMapXMLWithText(Map<?, ?> params, String root) {
        Element xml = DocumentHelper.createElement(root);

        for (Map.Entry<?, ?> entry : params.entrySet()) {
            xml.addElement((String) entry.getKey()).addText((String) entry.getValue());
        }

        return xml.asXML();
    }

    public static Map<String, String> xmlToMap(String xml) throws DocumentException {
        Map<String, String> result = new HashMap<>();

        Document doc = DocumentHelper.parseText(xml);
        Element root = doc.getRootElement();

        for (Iterator<Element> iterator = root.elementIterator(); iterator.hasNext(); ) {
            Element e = iterator.next();
            result.put(e.getName(), e.getText());
        }

        return result;
    }

}
